var params;
var intervalPay;
var payJson;
var channel;
var prepay_id = "";
var orderid = "";
var hychannel;
var hybusinessid;
var OPENID="";
var disabled=0;
var shoppingCart=[];
var shopping = {
	detail : {
		init : function(params) {
			var me = this;
			var _global = params;
			
			var shoppingCarKey = 'shoppingCar_' + _global.BUSINESS_ID;
			 
			
			// 用户的购物车
			shoppingCart = shopping.localData(shoppingCarKey)[_global.RAMADHIN];
			 
			 
			var foodHtml="";
			var payTotalPrice=new Decimal(0);
			$.each(shoppingCart,function(k,v){
				payTotalPrice=payTotalPrice.plus(new Decimal(v.food.price).times(v.food.quantity));
				foodHtml+='<dl><dt> <span>'+v.food.name.split("_")[0]+'</span>';
				if(v.food.name.split("_").length>1){
					foodHtml+='<span>--&nbsp;'+v.food.name.split("_")[1]+'</span> ';
				}
				foodHtml+='</dt><dd class="mui-text-center">￥'+v.food.price+'</dd>'+'<dd class="mui-text-right"><div class="choose-box"  menuid="';
				foodHtml+=v.menuId+'" price="'+v.food.price+'" foodid="'+v.food.foodId+'" foodname="'+v.food.name+'">';
				if(_global.withFee==0){
					foodHtml+='<span class="iconfont icon-tubiao reduceFood" style="color:#CFD1D0"></span>';
					foodHtml+='<em class="choose-number" style="border:0;width:18px;">';
				}
				foodHtml+=v.food.quantity;
				if(_global.withFee==0){
					foodHtml+='</em><span class="iconfont icon-add addFood add1" style="color:#CFD1D0;"></span>';
				}
				foodHtml+='</div></dd></dl>';
			});
			
			$("#Amount").html("￥"+payTotalPrice);
			var withfe=0;
			if(_global.withFee==1){
				withfe=new Decimal(0.006).times(payTotalPrice).plus(_global.serviceFee).ceil();
				if(withfe==0){
					withfe=0.01
				}
				$("#zk").html("￥"+withfe);
			}else{
				withfe=_global.serviceFee;
			}
		 
			$("#payTotalPrice").html("￥"+new Decimal(payTotalPrice).plus(withfe) );
			$("#listItemId").html(foodHtml);
			
			// 刷新购物车
			me.refreshLocalShoppingCar = function() {
				shopping.localData(shoppingCarKey, {
					key : _global.RAMADHIN,
					value : shoppingCart
				});
			}
			
			function changeTotalPrice(price){
				var payTotalPrice=$("#payTotalPrice").html().trim().substring(1);
				var payTotalPriceHtml ="￥"+new Decimal(parseFloat(payTotalPrice)).plus(parseFloat(price));
				$("#payTotalPrice").html(payTotalPriceHtml);
				$("#Amount").html(payTotalPriceHtml);
			}
			
			
			function removerSessionFood() {
				sessionStorage.clear();
			}
			 
			 // 支付按钮
			 $('#payBtn').on('click', function() {
					$(this).attr('disabled', "true");// 禁用
					$(this).html('待提交');
					 
					mui.ajax(rootpath + '/jhh/saveOrder.do', {
						data : {
							diningId : _global.trueRamadhin,
							note :  $("#REMARKS").val(),
							carFood: JSON.stringify(shoppingCart)
						},
						dataType : 'json',
						type : 'post',
						timeout : 10000,
						success : function(data) {
							 if(data.code==0){
								 if(data.channel=='wx'){
									 payJson=JSON.parse(data.payJson);
								 } 
								 me.clearCar();
								 orderid=data.orderId;
								 goPay(data.orderId,data.channel);
							 }
							 
						}
					});
			 });
			 
			// 总份数
			me.setTotalQuantity = function(number) {
				$('#totalQuantity').text(parseFloat($('#totalQuantity').text()) + number);
				if (parseFloat($('#totalQuantity').text()) == 0) {
					$('#payBtn').attr({
						"disabled" : "disabled"
					});
				}
			}
			// 菜单类别
			me.setMenuQuantity = function(dom, number) {
				var menu = $(dom).parent();
				var menuId = menu.attr('menuid');
				var menuQuantity = $('#' + menuId);
				menuQuantity.text(parseFloat(menuQuantity.text()) + number);
				var quantity = menuQuantity.text();
				if (quantity <= 0) {
					menuQuantity.parent().remove();
				}
			}
			// 共计多少钱
			me.totalAmount = function(price) {
			 
			}
			// 减少
			$(".reduceFood").on('click', function() {
				var amount = $(this).next();
				var amountParentNode = amount.parent();
				saveSessionItem(amountParentNode.attr('foodid'),-1);
				var amountVal = parseFloat(amount.html());
				if (amountVal > 0) {
					amount.html(amountVal - 1);
//					me.setTotalQuantity(-1);
					changeTotalPrice(-amountParentNode.attr('price'));
					me.addShoppingCart(amountParentNode, -1);
				}
				if (parseFloat(amount.html()) <= 0) {
					var listItem = $(this).parents('.listItem');
					$(this).parents('dl').remove();
					if (listItem.find('dl').length == 0) {
						listItem.remove();
					}
				}
//				me.refreshLocalShoppingCar();
				// 类别-1
//				me.setMenuQuantity(this, -1);
			});

			// 添加
			$(".addFood").on('click', function() {
				// 商品数量
				var amount = $(this).prev();

				var amountParentNode = amount.parent();
				saveSessionItem(amountParentNode.attr('foodid'),1);
				amount.html(parseFloat(amount.html()) + 1);
				 
				changeTotalPrice(amountParentNode.attr('price'));
				 
				me.addShoppingCart(amountParentNode, 1);
				// 类别+1
//				me.setMenuQuantity(this, 1);
//				me.refreshLocalShoppingCar();
			});

			// 商品加减都调用这个
			me.addShoppingCart = function(foodNode, quantity) {
				var quantity =quantity;
				var exist=0;
				for (i = 0; i < shoppingCart.length; i++) {
					if (shoppingCart[i].food.foodId == foodNode.attr('foodId')) {
						menuId=shoppingCart[i].food.menuId;
						var carFoodCount = shoppingCart[i].food.quantity + quantity ;
						if(carFoodCount<=0){
							shoppingCart.splice(i, 1);//移除
						}else{
							//更新购物车
							shoppingCart[i].food.quantity=carFoodCount;
						}
						exist=1;
						break;
					} 
				}
				if(exist==0){
				 
				}
				me.refreshLocalShoppingCar();
			};

			$("#clearCart").on('click', function() {
				mui.confirm('确认清空购物车吗？', '提示', [ '是', '否' ], function(e) {
					if (e.index == 0) {
						var shoppingCarKey = 'shoppingCar_' + _global.BUSINESS_ID;
						// 用户的购物车
						var shoppingCart = shopping.localData(shoppingCarKey)[_global.RAMADHIN];
						////me.clearCar();
						me.backCart();
					} else {
					}
				})
			});
		 
			// 清空缓存里面的商品信息
			me.clearCar = function() {
				shopping.localData(shoppingCarKey, {
					key : _global.RAMADHIN,
					remove : true
				});
				removerSessionFood();
			}
			 
	}
	},localData : function(table, settings) {
	table = table || 'shoppingCar';

	if (!window.JSON || !window.JSON.parse)
		return;

	// 如果settings为null，则删除表
	if (settings === null) {
		return delete localStorage[table];
	}

	settings = typeof settings === 'object' ? settings : {
		key : settings
	};

	try {
		var data = JSON.parse(localStorage[table]);
	} catch (e) {
		var data = {};
	}
	if (settings.value)
		data[settings.key] = settings.value;
	if (settings.remove)
		delete data[settings.key];
	localStorage[table] = JSON.stringify(data);
	return settings.key ? data[settings.key] : data;
}
};
//微信支付
function onBridgeReady(){
	   WeixinJSBridge.invoke(
	       'getBrandWCPayRequest', payJson,
	       function(res){     
	    	   var url = "";
				if (res.err_msg == "get_brand_wcpay_request:ok") {
					url = rootpath + "/jhh/payResult?orderId=" + orderid + "&action=success&prepay_id=" + prepay_id+"&OPENID="+OPENID;
				} else {
					url = rootpath + "/jhh/payResult?orderId=" + orderid + "&action=fail&prepay_id=" + prepay_id+"&OPENID="+OPENID;
				}
				window.location.href = url;     
	       }
	   ); 
	}
//去支付
function goPay(orderId,channel){
	if(channel=='wx'){//微信支付
		if (typeof WeixinJSBridge == "undefined"){
			   if( document.addEventListener ){
			       document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
			   }else if (document.attachEvent){
			       document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
			       document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
			   }
			}else{
			   onBridgeReady();
			}
	}else{//支付宝支付
		  location.href=rootpath+"/jhh/toAliPay.do?orderId="+orderId;
	}
	 
}
function saveSessionItem(foodtagId,val){
	var amount= sessionStorage.getItem("food"+foodtagId);
	if (typeof(amount) == "undefined") {
		amount=0;
	}
	var amountNumber=parseFloat(amount);
	sessionStorage.setItem("food"+foodtagId,amountNumber+val);
}